#!/bin/bash
source /etc/profile
. $BEETLE_SHELL_PATH/error.sh

start(){
    . /usr/local/python_vm/$1/bin/activate || error_exit "启动虚拟环境失败"

    codePath=/usr/local/beetle/code/$1
    logPath=/usr/beetle/applogs/$1/$1.log
    iniPath=$BEETLE_UWSGI_PATH/$1.ini

    cd ${codePath} || error_exit

    uwsgi --http-websockets --memory-report --disable-logging -d ${logPath} --ini ${iniPath} || error_exit

    tail -fn20 ${logPath}
}

start-s(){
    . /usr/local/python_vm/$1/bin/activate || error_exit "启动虚拟环境失败"

    codePath=/usr/local/beetle/code/$1
    logPath=/usr/beetle/applogs/$1/$1.log
    iniPath=$BEETLE_UWSGI_PATH/$1.ini

    cd ${codePath} || error_exit

    uwsgi --http-websockets --memory-report --disable-logging -d ${logPath} --ini ${iniPath} || error_exit

}

stop(){
    app=$1

    if [ -z ${app} ]; then
            echo "ini file name is none"
            exit 1
    fi

    pids=`ps -ef |grep -w uwsgi |grep -v grep|grep -v uwsgi.sh |grep ${app} |awk '{print $2}'`
    echo "uwsgi pids is [${pids}]"
    for pid in ${pids}; do
            kill -9 ${pid}
            echo "pid ${pid} is killd "
            sleep 1
    done
    pids=`ps -ef |grep -w uwsgi |grep -v grep |grep -v uwsgi.sh |grep ${app} |awk '{print $2}'`
    echo "uwsgi pids is [${pids}]"
    sleep 1
}

restart(){
    stop ${1}
    sleep 3
    start ${1}
}

projectName=$2

if [ ! ${projectName} ]
then
    error_exit "参数存在空值projectName"
fi

case "$1" in
    start)
        start ${projectName} ;;     
    stop)
        stop ${projectName} ;;
    restart)
        restart ${projectName} ;;
    start-s)
        start-s ${projectName} ;;         
    *)
    	echo "Usage: uwsgi {start|stop|restart} projectName"
    exit 1
esac
exit 0